package com.ruoyi.exam.websocket;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/pay/{orderNumber}")
@Component
public class PayWebSocket {

    private Session session;

    private static final Map<String, PayWebSocket> clients=new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session,@PathParam("orderNumber") String orderNumber){
        this.session=session;
        clients.put(orderNumber,this);
    }

    @OnClose
    public void onClose(Session session,@PathParam("orderNumber") String orderNumber){
        clients.remove(orderNumber);
    }

    @OnMessage
    public void onMessage(Session session,@PathParam("orderNumber") String orderNumber,String msg){

    }

    public static void sendPayResult(String orderNumber, JSONObject result) throws IOException {
        PayWebSocket payWebSocket = clients.get(orderNumber);
        if (payWebSocket==null){
            return;
        }
        payWebSocket.session.getBasicRemote().sendText(JSON.toJSONString(result));
    }
}
